package com.jic.manager.impl;

import com.alibaba.fastjson.JSONArray;
import com.jic.common.base.vo.Page;
import com.jic.common.base.vo.PageResult;
import com.jic.common.base.vo.RestResult;
import com.jic.common.redis.RedisClientTemplate;
import com.jic.manager.enums.ResponseCode;
import com.jic.manager.exception.AppRuntimeException;
import com.jic.manager.mapper.FileMapper;
import com.jic.manager.mapper.ProductCommentMapper;
import com.jic.manager.entity.File;
import com.jic.manager.entity.ProductComment;
import com.jic.conf.request.rest.UpdateProductCommentRequest;
import com.jic.manager.service.ProductCommentService;
import com.jic.enums.RedisKey;
import com.jic.order.api.OrderApi;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 商品评价表
 * @author : 
 * @email : 
 * @since : 2020-02-10 05:50:14
 * @version : v1.0.0
 */
@Slf4j
@Service
public class ProductCommentServiceImpl implements ProductCommentService {

    @Resource
    private ProductCommentMapper productCommentMapper;
    @Resource
    private FileMapper fileMapper;
    @Resource
    private OrderApi orderApi;
    @Resource
    private RedisClientTemplate redisClientTemplate;

    @Override
    public long insert(ProductComment productComment) {
        long flag = productCommentMapper.insert(productComment);
        return flag;
    }

    @Override
    public long delete(Long id) {
        return productCommentMapper.delete(id);
    }

    @Override
    public long update(ProductComment productComment) {
        return productCommentMapper.update(productComment);
    }

    @Override
    public ProductComment queryByPrimaryKey(Long id){
        return productCommentMapper.queryByPrimaryKey(id);
    }

    @Override
    public List<ProductComment> query(ProductComment productComment){
        return productCommentMapper.query(productComment);
    }

    @Override
    public PageResult<ProductComment> queryPage(ProductComment productComment, Page pageQuery) {
        //计算下标
        int startIndex = (pageQuery.getStart() - 1) * pageQuery.getLimit();
        List<ProductComment> list = productCommentMapper.queryPage(startIndex, pageQuery.getLimit(), productComment);
        long count = productCommentMapper.queryPageCount(productComment);
        PageResult pageResult = new PageResult();
        pageResult.setRows(list);
        pageResult.setTotal(count);
        return pageResult;
    }

    @Override
    public long queryCount(ProductComment productComment) {
        return productCommentMapper.queryPageCount(productComment);
    }

    @Transactional
    @Override
    public RestResult<String> updateProductComment(UpdateProductCommentRequest updateProductComment) {
        try {
            ProductComment productComment = new ProductComment();
            BeanUtils.copyProperties(updateProductComment, productComment);
            String token = updateProductComment.getToken();
            String memStr = redisClientTemplate.get(RedisKey.H5_LOGIN_TOKEN_.getName() + token);
            if (StringUtils.isEmpty(memStr)) {
                throw new AppRuntimeException(ResponseCode.NOT_LOGGED_IN);
            }
            Map memMap = JSONArray.parseObject(memStr, Map.class);
            Long memberId = Long.valueOf(memMap.get("id").toString());
            updateProductComment.getProductCommentGoodsRequests().forEach(apiProductCommentGoodsRequest -> {
                productComment.setType(updateProductComment.getType());
                productComment.setStatus(0);
                productComment.setMemberId(memberId);
                productComment.setMemberAccount(memMap.get("mobile").toString());
                productComment.setStickyStatus(0);
                productComment.setStartNum(0);
                productComment.setCreateTime(new Date());
                BeanUtils.copyProperties(apiProductCommentGoodsRequest, productComment);
                productCommentMapper.insert(productComment);

                List<String> fileList = apiProductCommentGoodsRequest.getFileList();
                if (CollectionUtils.isNotEmpty(fileList)) {
                    //新增图片
                    fileList.forEach(file -> {
                        fileMapper.insert(new File() {{
                            setType(0);
                            setUrl(file);
                            setBusinessId(productComment.getId());
                            setIsDelete("N");
                            setCreateTime(new Date());
                        }});
                    });
                }
            });

            if (updateProductComment.getType() == 1) {
                RestResult<Boolean> orderStatusResponse = orderApi.updateParentOrderStatus(updateProductComment.getOrderNo());
                if (!orderStatusResponse.getData()) {
                    throw new AppRuntimeException(ResponseCode.EXCEPTION, orderStatusResponse.getMsg());
                }
            }
            return RestResult.success("评价成功");
        } catch (RuntimeException e) {
            log.error("发表评价发生错误=========>>>>>>>>{}", e);
            throw new AppRuntimeException(ResponseCode.EXCEPTION);
        }
    }
}